<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col
              :md="6"
              :sm="10">
              <a-form-item label="选择项目">
                <a-select
                  show-search
                  :filter-option="filterOption"
                  placeholder="请选择项目"
                  @change="clearVersions"
                  v-model="queryParam.projectId">
                  <a-select-option
                    v-for="i in projectList"
                    :key="i.projectId"
                    :value="i.projectId">
                    {{ i.projectName }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col
              :md="6"
              :sm="6">
              <a-form-item label="选择版本">
                <a-select
                  style="width: 200px;margin-left: 15px"
                  v-model="version"
                  placeholder="请选择版本"
                  :disabled="hasGrant">
                  <a-select-option
                    v-for="i in allVersion"
                    :key="i"
                    :value="i">
                    {{ i }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col
              :md="12"
              :sm="10">
              <span
                class="table-page-search-submitButtons"
                :style="{ float: 'right', overflow: 'hidden' } || {} ">
                <!-- <a-button
                  type="primary"
                  :style="{ marginLeft: '10px' }"
                  @click="grant">导出报表</a-button> -->
                <a-button
                  type="primary"
                  :style="{ marginLeft: '10px' }"
                  @click="$refs.table.refresh()">查询</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
    <a-modal
      title="发放金额"
      :width="800"
      :bodyStyle="{height: '300px'}"
      :visible="visible"
      @ok="handleOk"
      @cancel="handleCancel">
      <div>
        <h3 style="margin-bottom: 80px;">该分配记录最高金额为：{{ maxAmount }}</h3>
        <span>请输入金额：</span>
        <a-input-number
          :min="0"
          :max="maxAmount"
          v-model="amount"
          :precision="2"
          placeholder="请输入金额" />
        <span style="margin-left: 20px;">备注：</span>
        <a-textarea
          style="width: 300px;position: absolute;height: 80px;"
          v-model="note"
          placeholder="请输入" />
      </div>
    </a-modal>
    <s-table
      ref="table"
      size="default"
      rowKey="performanceConfigId"
      :columns="columns"
      :data="loadData"
      :customRow="tableCustomRow"
      :showPagination="false">
      <span
        slot="createTime"
        slot-scope="text, record">
        {{ record.createTime.split(' ')[0] }}
      </span>
      <span
        slot="content"
        slot-scope="text">
        <ellipsis
          :length="20"
          tooltip>{{ text }}</ellipsis>
      </span>
      <span
        slot="name"
        slot-scope="text, record">
        <span :class="`record${record.level || ''}`">{{ text }}</span>
      </span>
      <span
        slot="job2"
        slot-scope="text">
        <span>{{ labels.find(item => item.value === text) ? labels.find(item => item.value === text).label : '' }}</span>
      </span>
      <!-- contractName -->
      <span
        slot="projectName"
        slot-scope="text">
        <ellipsis
          :length="40"
          tooltip>{{ text }}</ellipsis>
      </span>
      <span
        slot="note"
        slot-scope="text">
        <ellipsis
          :length="20"
          tooltip>{{ text }}</ellipsis>
      </span>
      <span
        slot="action"
        slot-scope="text, record">
        <template>
          <a
            v-if="record.level === 1"
            @click="grant(record)">发放</a>
          <div>
            <a
              v-if="!record.level"
              @click="deleteRules(record)">撤销</a>
          </div>
          <div>
            <a
              v-if="!record.level"
              @click="updateAmount(record)">更新金额</a>
          </div>
        </template>
      </span>
    </s-table>
  </page-header-wrapper>
</template>

<script>
import moment from 'moment'
import { STable, Ellipsis } from '@/components'
import { initialGrantList, grantIncentive, updateIncentive, deleteIncentive } from '@/api/incentiveGrant'
import CreateForm from './modules/CreateForm'
import { columns } from './mock.js'
import { mapGetters } from 'vuex'
import { message, Modal } from 'ant-design-vue'
import { getProjectList } from '@/api/manage'
import {
  getRelatedVersions // .查询已关联绩效参数年份版本
} from '@/api/incentive'
export default {
  name: 'TableList',
  components: {
    STable,
    Ellipsis,
    CreateForm
  },
  data () {
    this.columns = columns
    return {
      // 权限参数
      list: false, // 列表
      save: false, // 家
      deleteBtn: false, // 删
      update: false, // 改
      detail: false, // 详情
      projectList: [],
      labels: [
        { label: '全职业务员提成', value: 1 },
        { label: '兼职业务员提成', value: 2 },
        { label: '项目经理提成', value: 3 },
        { label: '策划组提成', value: 4 },
        { label: 'UI设计&动效创意组提成 ', value: 5 },
        { label: '程序组提成 ', value: 6 },
        { label: '内容组(定制软件)提成', value: 7 },
        { label: '硬件开发组(定制硬件)提成', value: 8 },
        { label: '行政管理提成', value: 9 },
        { label: '项目组提成', value: 10 }
      ],
      // create model
      visible: false,
      confirmLoading: false,
      incentive: {},
      allVersion: [],
      version: undefined,
      hasGrant: false,
      // 区分发放还是更新
      isGrant: false,
      // 查询参数
      queryParam: {},
      id: '',
      // 最大发放金额，发放金额
      maxAmount: 0,
      amount: 0,
      note: '',
      // 加载数据方法 必须为 Promise 对象
      loadData: async parameter => {
        if (!this.queryParam.projectId) return Promise.resolve({ data: [] })
        let targetVersion
        await getRelatedVersions(this.queryParam).then(res => {
          this.hasGrant = res.data.some(item => item.flg === 'Y')
          targetVersion = res.data.find(item => item.flg === 'Y') || res.data?.[0]
          this.allVersion = res.data.map(item => `${item.year}/${item.version}`)
          this.version = this.allVersion.includes(this.version) ? this.version : (targetVersion ? `${targetVersion.year}/${targetVersion.version}` : undefined)
        })

        if (!this.version) return Promise.resolve({ data: [] })
        const [year, version] = this.version.split('/')
        const res = await initialGrantList({ ...this.queryParam, year, version })
        this.projectId = this.queryParam.projectId
        res.data.forEach(item => {
          item.level = 1
        })
        return Promise.resolve({ data: res.data })
      },
      staffInfo: {},
      selectedRowKeys: [],
      selectedRows: [],
      physicalSurveyCurrRowId: null
    }
  },
  computed: {
    ...mapGetters(['menu'])
  },
  created () {},
  mounted () {
    // 查询所有的项目类型
    getProjectList({ page: 0, limit: 999 }).then(res => {
      this.projectList = res.data
    })
  },
  methods: {
    handleAdd () {
      this.$refs.createModal.form.resetFields()
      this.isAdd = true
      this.visible = true
    },
    clearVersions () {
      this.version = ''
      this.hasGrant = false
      this.allVersion = []
    },
    handleEdit (record) {
      this.$refs.createModal.form.resetFields()
      const form = this.$refs.createModal.form
      this.isAdd = false
      this.visible = true
      this.$nextTick(() => {
        form.setFieldsValue(record)
      })
    },
    // updateAmount
    updateAmount (record) {
      this.visible = true
      this.incentive = record
      this.id = record.incentiveGrantId
      this.isGrant = false
      this.note = record.note
      this.amount = record.amount
      this.maxAmount = this.$refs.table._data.localDataSource.find(
        item => item.performanceConfigId === record.performanceConfigId
      ).amount
    },
    // 发放金额
    grant (record) {
      this.visible = true
      this.maxAmount = record.amount
      this.incentive = record
      this.id = record.performanceConfigId
      this.isGrant = true
      this.note = ''
    },
    async handleOk () {
      this.confirmLoading = true
      const projectId = this.projectId
      if (this.isGrant) {
        const { job2, incentiveName, userId } = this.incentive
        await grantIncentive({
          projectId,
          amount: this.amount,
          job2,
          performanceConfigId: this.id,
          incentiveName,
          note: this.note,
          userId
        })
          .then(() => {
            this.$refs.table.refresh()
            message.success('发放操作成功')
          })
          .finally(() => {
            this.confirmLoading = false
            this.visible = false
            this.note = ''
          })
      } else {
        await updateIncentive({
          incentiveGrantId: this.id,
          amount: this.amount,
          note: this.note
        })
          .then(() => {
            this.$refs.table.refresh()
            message.success('更新操作成功')
          })
          .finally(() => {
            this.confirmLoading = false
            this.visible = false
            this.note = ''
          })
      }
    },
    handleCancel () {
      this.visible = false
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    resetSearchForm () {
      this.queryParam = {
        date: moment(new Date())
      }
    },
    deleteRules (record) {
      Modal.confirm({
        title: '撤销发放',
        content: '删除后数据不再展示，但仍保留在数据库中，需要查看请联系开发',
        onOk: async () => {
          await deleteIncentive({ incentiveGrantId: record.incentiveGrantId })
          this.$refs.table.refresh()
          message.success('删除成功')
        }
      })
    },
    filterOption (input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    tableCustomRow (record, index) {
      return {
        style: {
          'background-color':
            `${record.performanceConfigId}-${record.incentiveGrantId || ''}${record.job2}${record.userId}` ===
            this.physicalSurveyCurrRowId
              ? '#dff3fe'
              : 'white'
        },
        on: {
          click: event => {
            this.physicalSurveyCurrRowId = `${record.performanceConfigId}-${record.incentiveGrantId || ''}${
              record.job2
            }${record.userId}`
            this.conRecord = record
          }
        }
      }
    }
  }
}
</script>
<style lang="less" scoped>
.record {
  margin-left: 20px;
}
/deep/.ant-input-number {
  // width: fit-content;
  width: 200px;
}
/deep/.ant-input-number-handler-wrap {
  display: none;
}
/deep/.ant-card-grid {
  padding: 24px 0;
}
</style>
